package com.lagou.edu.service.impl;

import com.lagou.edu.constant.CodeValidateResult;
import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.AuthCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class AuthCodeServiceImpl implements AuthCodeService {
    private static final int EXPIRE_DURATION_MINUTES = 10;

    @Autowired
    private AuthCodeDao authCodeDao;

    @Override
    public String create(String email) {
        // 生成6位随机数验证码
        String code = generateCode();
        long currentTime = System.currentTimeMillis();
        long expireTime = currentTime + EXPIRE_DURATION_MINUTES * 60 * 1000;
        AuthCode authCode = AuthCode.builder()
                .code(code)
                .email(email)
                .createTime(formatTime(currentTime))
                .expireTime(formatTime(expireTime))
                .build();
        // 保存到验证码表
        authCodeDao.save(authCode);
        return code;
    }

    @Override
    public int validate(String email, String code) {
        AuthCode authCode = AuthCode.builder().email(email).code(code).build();
        Example<AuthCode> example = Example.of(authCode);
        Sort sort = new Sort(Sort.Direction.DESC,"expireTime");
        List<AuthCode> all = authCodeDao.findAll(example, sort);
        log.info("auth codes found：{}", all);
        if (all.isEmpty()) {
            return CodeValidateResult.INCORRECT;
        }

        AuthCode latestAuthCode = all.get(0);
        String expireTime = latestAuthCode.getExpireTime();
        String currentTime = formatTime(System.currentTimeMillis());
        return expireTime.compareTo(currentTime) > 0 ? CodeValidateResult.CORRECT : CodeValidateResult.TIMEOUT;
    }

    private String generateCode() {
        // 生成[0, 999999]范围内的随机数
        int number = new Random().nextInt(1000000);
        // 不足6位补零
        return String.format("%06d", number);
    }

    private String formatTime(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(time);
    }
}
